from nicegui import ui
from typing import Callable,List
from dataclasses import dataclass,field
import time

@dataclass(order=True)
class TodoItem:
    name: str = field(compare=False)
    done: bool = False

@dataclass
class ToDoList:
    title: str 
    on_change: Callable
    items: List[TodoItem] = field(default_factory=list)
    def add(self,name:str,done:bool=False)->None:
        self.items.append(TodoItem(name,done))
        self.on_change()
    
    def remove(self,item: TodoItem)->None:
        self.items.remove(item)
        self.on_change()
        
@ui.refreshable
def todo_ui():
    print("666")
    if not todos.items:
        ui.label("List is empty.")
        return
    ui.linear_progress(sum(item.done for item in todos.items) / len(todos.items), show_value=False)
    
    with ui.row():
        ui.label(f"Completed:{sum(item.done for item in todos.items)}")
        ui.label(f"Remaining:{sum(not item.done for item in todos.items)}")
    
    for item in sorted(todos.items):
        with ui.row():
            ui.checkbox(value = item.done,on_change=todo_ui.refresh).bind_value(item,'done')
            ui.input(value=item.name).bind_value(item,"name")
            ui.button(on_click = lambda item=item: todos.remove(item),icon='delete').props('flat fab-mini color=grey')

todos = ToDoList(f"{time.strftime('%Y')}年{time.strftime('%W')}周",on_change=todo_ui.refresh)
todos.add('Order pizza', done=True)
todos.add('New NiceGUI Release')
todos.add('Clean the house')
todos.add('Call mom')

with ui.card().classes("w-80 items-stretch"):
    ui.label().bind_text_from(todos,'title').classes('text-semibold text-2xl')
    todo_ui()
    add_input=ui.input('new item').classes('mx-12')
    add_input.on('keydown.enter',lambda:(todos.add(add_input.value),add_input.set_value("")))
ui.run(native=True,reload=False)